// Flutter imports:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

// Package imports:
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:palmf_hid/common/entities/data_base/my_database.dart';
import 'package:palmf_hid/common/services/Db.dart';
import 'package:palmf_hid/common/utils/utils.dart';
import 'package:palmf_hid/common/values/values.dart';
import 'package:palmf_hid/common/widgets/dropdown_button/dropdown_button_view.dart';
import 'package:palmf_hid/common/widgets/empty_widget.dart';
import 'package:palmf_hid/common/widgets/input_screening_widget.dart';
import 'package:palmf_hid/common/widgets/logout_widget.dart';
import 'package:palmf_hid/common/widgets/my_app_bar.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

// Project imports:

import 'data_back_dialog.dart';
import 'history_item.dart';
import 'show_history_data_logic.dart';

class ShowHistoryDataPage extends StatefulWidget {
  Function onDisConnectAll;
  Function needRefresh;
  Function onPrint;
  Function onDeleteAll;

  ShowHistoryDataPage(
      {Key? key,
      required this.onDisConnectAll,
      required this.needRefresh,
      required this.onDeleteAll,
      required this.onPrint})
      : super(key: key);

  @override
  State<ShowHistoryDataPage> createState() => _ShowHistoryDataPageState(
      onDisConnectAll, needRefresh, onPrint, onDeleteAll);
}

class _ShowHistoryDataPageState extends State<ShowHistoryDataPage> {
  final logic = Get.put(ShowHistoryDataLogic());
  final state = Get.find<ShowHistoryDataLogic>().state;
  Function onDisConnectAll;
  Function needRefresh;
  Function onPrint;
  Function onDeleteAll;

  _ShowHistoryDataPageState(
      this.onDisConnectAll, this.needRefresh, this.onPrint, this.onDeleteAll);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar:
            myAppBar(titleName: "historicalData".tr, action: _buildAction()),
        body: Obx(() => _buildBody()));
  }

  _buildAction() {
    return [
      Padding(
          padding: const EdgeInsets.only(right: 10),
          child: DropdownButtonPage(
            func: ["backup".tr, "restore".tr, "deleteALLData".tr],
            funcIcon: const [Icons.backup, Icons.restore_rounded, Icons.delete],
            onSelect: (v) {
              MyLogUtil().i(v);
              if (null != v && v != -1) {
                switch (v) {
                  case 0:
                    showDialog(
                        context: Get.context!,
                        builder: (ctx) {
                          return buildDataBackDialog(
                              str: "dataBackNotice".tr,
                              onPress: () {
                                logic.backupData();
                              });
                        });
                    break;
                  case 1:
                    showDialog(
                        context: Get.context!,
                        builder: (ctx) {
                          return buildDataBackDialog(
                              str: "dataRestoreNotice".tr,
                              onPress: () {
                                logic.restoreData().then((value) {
                                  if (value) {
                                    logic.needRefresh();
                                  }
                                });
                              });
                        });
                    break;
                  case 2:
                    Get.bottomSheet(
                        logoutWidget(
                            title: "deleteHistory".tr,
                            fucName: "deleteALLData".tr,
                            onSelect: () async {
                              await DbService.to.removeAllHistory();
                              Get.back();
                              logic.refreshController.requestRefresh();
                              // logic.dataBackLogic.getHistoryList();
                            },
                            onCancel: () {
                              Get.back();
                            }),
                        backgroundColor: Colors.transparent,
                        elevation: 0);
                    break;
                }
              }
            },
          ))
    ];
  }

  _buildBody() {
    return SafeArea(
        maintainBottomViewPadding: true,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            _buildSearch(),
            const SizedBox(
              height: 5,
            ),
            Expanded(
                child: Container(
                    padding:
                        const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                    child: SmartRefresher(
                      key: logic.refresherKey,
                      header: ClassicHeader(
                        completeText: "Refresh complete".tr,
                        releaseText: "refresh".tr,
                        refreshingText: "refresh".tr,
                        idleText: "Pull down refresh".tr,
                        failedText: "Refresh failure".tr,
                      ),
                      footer: CustomFooter(
                        builder: (BuildContext? context, LoadStatus? mode) {
                          Widget body;
                          if (mode == LoadStatus.idle) {
                            body = Text("Pull-up loading".tr);
                          } else if (mode == LoadStatus.loading) {
                            body = const CupertinoActivityIndicator();
                          } else if (mode == LoadStatus.failed) {
                            body = Text("Load failed, try again!".tr);
                          } else if (mode == LoadStatus.canLoading) {
                            body = Text("Let go and load more!".tr);
                          } else {
                            body = Text("No more data".tr);
                          }
                          return SizedBox(
                            height: 55.0,
                            child: Center(child: body),
                          );
                        },
                      ),
                      controller: logic.refreshController,
                      enablePullUp: true,
                      enablePullDown: true,
                      onRefresh: logic.onRefresh,
                      onLoading: logic.onLoading,
                      child: state.historyResultList.isEmpty
                          ? Center(
                              child: emptyWidget(),
                            )
                          : ListView.separated(
                              separatorBuilder: (_, index) => const Divider(
                                    height: 10,
                                    thickness: 1,
                                  ),
                              itemBuilder: (context, index) => historyItem(
                                  index: index,
                                  item: state.historyResultList[index],
                                  onDelete: (Results result) {
                                    DbService.to
                                        .deleteHistoryRecordById(result.id)
                                        .then((value) async {
                                      if (value > 0) {
                                        MyLogUtil().i("str");
                                        state.historyResultList.removeAt(index);
                                        if (state.historyResultList.length <
                                            10) {
                                          logic.refreshController
                                              .requestRefresh();
                                        }
                                        state.total = await DbService
                                            .to.allResultDataCount;
                                        logic.refreshController
                                            .requestRefresh();
                                        // logic.dataBackLogic.getHistoryList();
                                      } else {
                                        MyToastUtil.show("fail".tr);
                                      }
                                    });
                                  },
                                  onPrint: (Results result) {
                                    onPrint(result);
                                  }),
                              itemCount: state.historyResultList.length),
                    ))),
            const Divider(
              height: 1,
            )
          ],
        ));
  }

  ///时间内容装饰器
  _buildTimeContainer({required String time, required int type}) {
    return Container(
        height: 30,
        padding: const EdgeInsets.symmetric(horizontal: 5),
        margin: const EdgeInsets.all(0),
        alignment: Alignment.centerLeft,
        decoration: BoxDecoration(
            border: Border.all(
              color: MyColor.c_FFEAEAEA,
              width: 1,
            ),
            borderRadius: BorderRadius.circular(4),
            color: MyColor.c_FFFFFFFF),
        child: Row(
          children: [
            Expanded(
                child: InkWell(
                    child: Text(
                      time,
                      style: const TextStyle(
                          fontSize: 12, color: MyColor.c_66000000),
                    ),
                    onTap: () {
                      logic.showDateSelect(type);
                    })),
            type == 0 && state.startTime == "" ||
                    type == 1 && state.endTime == ""
                ? const SizedBox()
                : InkWell(
                    child: const Icon(
                      Icons.close_rounded,
                      size: 20,
                      color: MyColor.c_99000000,
                    ),
                    onTap: () {
                      if (type == 0) {
                        state.startTime = "";
                      } else {
                        state.endTime = "";
                      }
                    },
                  )
          ],
        ));
  }

  ///搜索框
  Widget _buildSearch() {
    return Container(
        height: 80,
        color: Colors.white,
        padding: const EdgeInsets.symmetric(horizontal: 10),
        width: 1.sw,
        child: Row(
          children: [
            Expanded(
                child: Column(children: [
              inputScreeningWidget(
                  searchFocusNode: logic.searchFocusNode,
                  textEditingController: logic.textEditingController,
                  onChange: (e) {
                    state.searchContent = e.toString();
                    if (e.toString().isNotEmpty) {
                      state.total = -1;
                    }
                  },
                  onSubmitted: () {
                    logic.handleSearch();
                  },
                  close: state.searchContent == ""
                      ? const SizedBox()
                      : InkWell(
                          child: const Icon(
                            Icons.close,
                            size: 18,
                          ),
                          onTap: () {
                            state.searchContent = "";
                            logic.textEditingController.text = "";
                          },
                        ),
                  keyboardType: TextInputType.text,
                  hintText: 'Please enter a project'.tr),
              const SizedBox(
                height: 10,
              ),
              SizedBox(
                  height: 30,
                  child: Row(
                    children: [
                      Expanded(
                          child: _buildTimeContainer(
                              time: state.startTime == ""
                                  ? "startTime".tr
                                  : state.startTime,
                              type: 0)),
                      const SizedBox(width: 10),
                      Expanded(
                          child: _buildTimeContainer(
                              time: state.endTime == ""
                                  ? "endTime".tr
                                  : state.endTime,
                              type: 1)),
                    ],
                  ))
            ])),
            const SizedBox(
              width: 10,
            ),
            InkWell(
                child: Container(
                  height: 40,
                  padding:
                      const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                  decoration: BoxDecoration(
                      color: Colors.blue,
                      border: Border.all(color: Colors.white, width: 1.0),
                      borderRadius: const BorderRadius.all(Radius.circular(5))),
                  child: Center(
                    child: Text(
                      "screening".tr,
                      style: const TextStyle(color: Colors.white, fontSize: 12),
                    ),
                  ),
                ),
                onTap: () {
                  logic.handleSearch();
                }),
          ],
        ));
  }

  @override
  void dispose() {
    Get.delete<ShowHistoryDataLogic>();
    super.dispose();
  }
}
